package com.example;

import java.net.InetAddress;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.Scanner;

import org.jnetpcap.Pcap;
import org.jnetpcap.PcapHeader;
import org.jnetpcap.PcapIf;
import org.jnetpcap.PcapIf.PcapAddr;
import org.jnetpcap.constant.SockAddrFamily;
import org.jnetpcap.util.PcapUtils;

import com.example.Utils;
import com.example.Packet;
import com.example.Config;

public class Main {
    public static void main(String[] args) throws Exception {
        Config cfg = Config.parseArgs(args);

//        System.out.printf("address: %s%n", cfg.address.getHostAddress());
//        System.out.printf("port: %d%n", cfg.port);

//        cfg.path().ifPresentOrElse((path) -> System.out.printf("path: %s%n", path), () -> System.out.println("No path"));

        String request;
        if (cfg.path().isEmpty()) {
            Scanner scanner = new Scanner(System.in);
            StringBuilder input = new StringBuilder();

            System.out.println("Enter lines of text (an empty line to quit):");

            while (true) {
                String line = scanner.nextLine();

                // 如果输入的是一个空行，就退出循环
                if (line.isEmpty()) {
                    break;
                }

                input.append(line).append("\r\n");
            }

//            System.out.println("You entered:");
//            System.out.println(input.toString());
            request = input.toString();

            scanner.close();
        } else {
            request = "GET " + cfg.path().get() + " HTTP/1.1\r\n" + "Host:" + cfg.address.getHostAddress() + ":" + cfg.port + "\r\n\r\n";
        }

        HttpClient.HttpResponse response = HttpClient.sendRequest(request, cfg.address.getAddress(), cfg.port);

        System.out.println();

        System.out.println(response.status);
        response.fields.forEach(System.out::println);
        System.out.println();
        String decodedBody = decodeText(response.body);
        if (decodedBody != null) {
            System.out.println(decodedBody);
        }
        Files.write(Path.of("response.bin"), response.body, StandardOpenOption.CREATE);

    }

    /**
     * Tries to decode a byte array as a UTF-8 string.
     *
     * @param bytes the byte array to decode
     * @return the decoded string if the byte array can be decoded as a UTF-8 string, null otherwise
     */
    public static String decodeText(byte[] bytes) {
        CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder();
        try {
            return decoder.decode(ByteBuffer.wrap(bytes)).toString();
        } catch (CharacterCodingException e) {
            return null;
        }
    }

}
